package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.auth.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String KEY_PREFIX = "user:verify:code:phone:";

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    AmqpTemplate amqpTemplate;

    /**
     * 为了防止数据非法我们会在controller层进行加密
     * @param data 用户名或手机号
     * @param type 数据类型：1是用户名；2是手机；其它是参数有误
     * @return true：可以使用; false：不可使用
     */
    @Override
    public Boolean exists(String data, Integer type) {
        System.out.println("data = " + data);
        System.out.println("type = " + type);
        if ((type == 1 || type == 2) == false) {
            throw new LyException(400, "请求参数有误");
        }
        System.out.println("-------------------<<<<<<<<<<<<<<<<<<<<");
        return query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    /**
     * 发送短信验证码
     * @return 无
     */
    //- 生成随机验证码
    //- 将验证码保存到Redis中，用来在注册的时候验证
    //- 发送验证码到ly-sms-service服务，发送短信
    @Override
    public void sendCode(String phone) {
        // 对手机号验证
        if(!RegexUtils.isPhone(phone)){
            throw new LyException(400, "手机号格式不正确！");
        }
        //生成验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "8888";

        //保存在redis中,五分钟失效
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);

        //发送mq，和上面业务对接
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        System.out.println("---------------------------------???????");
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Override
    public void register(User user, String code) {
        //取出redis验证码
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        System.out.println("redisCode = " + redisCode);
        //比较验证码
        if (StringUtils.equals(code,redisCode)==false){
            throw new LyException(404,"验证码错误");
        }
        //对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        System.out.println("注册用户==>"+user);
        save(user);
    }

    //查询时也要对密码进行加密后判断是否一致
    //查询时数据库得到的加密密码就有原来的加盐值和加盐次数
    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {
        if (username==null||password==null){
            throw new LyException(400,"错误请求参数");
        }
        //数据库查询
        //底层为对我们传入的密码再次加盐加密，再与数据库中的密码做对比
        System.out.println("------------------------->username");
        //User user = query().eq("username", username).one();
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        System.out.println("查询出来的user = " + user);
        if (passwordEncoder.matches(password,user.getPassword())==false){
            throw new LyException(400,"用户名或者密码错误");
        }
        //转换为DTO
        return new UserDTO(user);
    }
}